package com.zrh.jsd.service.studydemo.local_persistence;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zrh.jsd.common.model.UserRecord;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class BufferWriterSaveFile {
    static String filename = "D:/a/string.txt";

    public static void main(String[] args) throws IOException {
//        writeMethod(10000);

        List<UserRecord> list = readMethod(UserRecord.class);
        System.out.println(list);
    }

    public static <T> List<T> readMethod(Class<T> tClass) throws IOException {
        File f = new File(filename);

        Long start = System.currentTimeMillis();
        InputStreamReader reade = new InputStreamReader(new FileInputStream(f));
        BufferedReader reader = new BufferedReader(reade);
        String a = reader.readLine();
        String[] split = a.split("&j");
        List<T> list = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            list.add(JSONObject.parseObject(split[i], tClass));
        }
        System.out.println("耗时=====" + (System.currentTimeMillis() - start));
        System.out.println(list.size());
        return list;
    }

    public static void writeMethod(int num)  {
        File f = new File(filename);
        String s = getUserList(num);
        Long start = System.currentTimeMillis();
        try(FileOutputStream fileOutputStream = new FileOutputStream(f, true);
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            BufferedWriter writer = new BufferedWriter(outputStreamWriter);
        ){
            writer.write(s);
            System.out.println("耗时=====" + (System.currentTimeMillis() - start));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getUserList(int num) {
        StringBuilder stringResult = new StringBuilder();
        String id = UUID.randomUUID().toString();
        for (int i = 0; i < num; i++) {
            stringResult.append(JSONArray.toJSON(new UserRecord(id, id, id, id, i * 100, i * 100, new Date())) + "&j");
        }
        return stringResult.toString();
    }
}
/*
 * 1000  23
 *
 * */
